package com.leo.leetcode.s100;

/**
 *
 * @author xuexiaolei
 * @version 2017年11月17日
 */
public class T08atoi {
    public static int myAtoi(String str) {
        char[] cs = str.toCharArray();
        boolean begin = false;//是否开始寻找数字了？
        boolean isNegative = false;
        long result = 0;
        for (int i = 0; i < str.length(); i++) {
            char tmp = cs[i];
            if (!begin && tmp==' ') {continue;}
            if (!begin && tmp=='+') {begin=true; continue;}
            if (!begin && tmp=='-') {isNegative=true; begin=true; continue;}
            if (!begin && tmp>='0' || tmp<='9'){ begin = true; }
            if (!begin && (tmp<'0' || tmp>'9')){ return 0; }

            if (begin && (tmp<'0' || tmp>'9')){ break; }
            result = result*10 + (tmp-'0');

            //检验
            long tmpR = isNegative?-result:result;
            if (tmpR < Integer.MIN_VALUE) { return Integer.MIN_VALUE; }
            if (tmpR > Integer.MAX_VALUE) { return Integer.MAX_VALUE; }
        }

        return (int) (isNegative?-result:result);
    }

    public static void main(String[] args) {
        System.out.println(myAtoi("123"));
        System.out.println(myAtoi("123a"));
        System.out.println(myAtoi("-123"));
        System.out.println(myAtoi("   -123"));
        System.out.println(myAtoi("   -123abc"));
        System.out.println(myAtoi("   --123abc"));//0
        System.out.println(myAtoi("2147483647"));//0
        System.out.println(myAtoi("2147483648"));//0
    }
}
